<template>
  <a-spin :spinning="isLoading">
    <page-layout>
      <a-row :gutter="[10, 10]">
        <a-col :span="24">
          <a-card>
            <footer-button :buttons="formState.buttons" />
            <a-form
              ref="formRef"
              :model="formState.state"
              :rules="formRules"
              :label-col="labelCol"
              :wrapper-col="wrapperCol"
            >
              <a-row>
                <a-col :span="8">
                  <a-form-item label="编号" name="code">
                    <a-input v-model:value="formState.state.code" readonly :maxlength="50"   placeholder="自动生成" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="联系人姓名" name="contactsName">
                    <a-input v-model:value="formState.state.contactsName" :maxlength="50"   placeholder="请输入" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="所属部门" name="contactsDepartment">
                    <a-input v-model:value="formState.state.contactsDepartment" :maxlength="100" placeholder="请输入" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="职位" name="contactsPosition">
                    <a-input v-model:value="formState.state.contactsPosition" :maxlength="100" placeholder="请输入" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-item label="所属学校" name="schName">
                    <a-input v-model:value="formState.state.schName" readonly placeholder="请选择">
                      <template #addonAfter>
                        <div class="primary-color cursor-pointer" @click="openDialog('schName')">选择</div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="负责人" name="responsiblePerson">
                    <a-input v-model:value="formState.state.responsiblePerson" placeholder="请选择">
                      <template #addonAfter>
                        <div class="primary-color cursor-pointer" @click="openDialog('responsiblePerson')">选择</div>
                      </template>
                    </a-input>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="电话" name="contactsPhone">
                    <a-input v-model:value="formState.state.contactsPhone" placeholder="请输入" :maxlength="40" />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-item label="邮箱" name="contactsEmail">
                    <a-input v-model:value="formState.state.contactsEmail" placeholder="请输入" :maxlength="50" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="性别" name="contactsSex">
                    <a-select v-model:value="formState.state.contactsSex" placeholder="请选择">
                      <a-select-option v-for="item in dictLists.data['sex']"
                                       :key="item.id" :value="item.value"
                      >{{ item.label }}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="状态" name="contactsState">
                    <a-select v-model:value="formState.state.contactsState" placeholder="请选择">
                      <a-select-option v-for="item in dictLists.data['contact_status']"
                                       :key="item.id" :value="item.value"
                      >{{ item.label }}</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="8">
                  <a-form-item label="办公地址" name="contactsOfficeAddress">
                    <a-input v-model:value="formState.state.contactsOfficeAddress" :maxlength="100" placeholder="请输入" />
                  </a-form-item>
                </a-col>
                <a-col :span="8">
                  <a-form-item label="备注" name="remark">
                    <a-textarea v-model:value="formState.state.remark" :maxlength="500" :rows="2" placeholder="请输入"/>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </a-card>
        </a-col>
      </a-row>
      <BasicTableModal v-model:visible="modalConfig.show"
                       v-if="modalConfig.show"
                       :columns="modalConfig.commonColumns"
                       :fetchAjax="modalConfig.api"
                       :title="modalConfig.title"
                       :searchForm="modalConfig.searchForm"
                       @selectUniversity="value => selectItem(value, modalConfig.currentType)" />
    </page-layout>
  </a-spin>
</template>
<script>
export default {
  name: 'college-manage-add',
}
</script>
<script setup>
import { save, selectById, update } from "@/api/module/contact-manage";
import {onMounted, reactive, ref,watch, 
onBeforeMount, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted} from "vue";
import {useRoute, useRouter} from 'vue-router'
import { getDictByCodesReturnObj } from '@/tools/get-dict'
import dictEnum from '@/const/dict'
import { page as schoolPage } from '@/api/module/school'
import { page as userPage } from '@/api/module/user'
import BasicTableModal from '@/component/basic-table-modal'
import {message} from "ant-design-vue";
import mixin from '@/mixins'

import { emailPattern, phoneCardPattern} from '@/utils/validator'
const { returnRoute } = mixin.setup()
let isLoading = ref(false)
const formRef = ref();
const route = useRoute()
const router = useRouter()
const formState = reactive({
  buttons: [
    {
      name: 'save',
      event: () => onSubmit(),
      type: "primary",
      code: ''
    },
    {
      name: 'reset',
      event: () => resetForm(),
      code: ''
    }
  ],
  state: {
    contactsName: '',
    contactsDepartment: '',
    contactsPosition: '',
    schId: '',
    schName: '',
    responsiblePerson: '',
    responsiblePersonId: '',
    contactsPhone: '',
    contactsEmail: '',
    contactsSex: null,
    contactsState: null,
    contactsOfficeAddress: '',
  }
});
const saveKey = "save";
const labelCol = { span: 6 }
const wrapperCol = { span: 18 }
let dictLists = reactive({
  data: {}
})
const modalConfig = reactive({
  title: '选择学校',
  api: schoolPage,
  show: false,
  currentType: '',
  commonColumns: [],
  universityColumns: [],
  responsibleColumns: [],
  searchForm: []
})
const formRules = {
  contactsName: [ { required: true, message: '请输入联系人姓名', trigger: 'blur'} ],
  contactsDepartment: [ { required: true, message: '请输入所属部门', trigger: 'blur'} ],
  contactsEmail: [ { required: true, validator: (rules, value) => {
    if (!value) return Promise.reject('请输入邮箱地址')
    if (value && !emailPattern.test(value)) {
      return Promise.reject('请输入正确的邮箱地址')
    }
    return Promise.resolve()
  }, trigger: 'blur'} ],
  // contactsPhone: [ { required: false, validator: (rules, value) => {
  //   if (!value) return Promise.resolve()
  //   if (value && !phoneCardPattern.test(value)) {
  //     return Promise.reject('请输入正确的电话号码')
  //   }
  //   return Promise.resolve()
  // }, trigger: 'blur'} ],
};

// watch(route, () => {
//   getList()
// });

const getList = ()=>{
  formRef.value.resetFields()
  if (route.query.id) {
    selectById({id: route.query.id}).then(res => {
      if (res.code === 200) {
        formState.state = {
          ...formState.state,
          ...res.data
        }
      }
      if (res.code === 500) return message.error(res.msg || '服务器错误')
    })
  }
}
onMounted(async () => {
  getList()
  dictLists.data = await getDictByCodesReturnObj([
    dictEnum.FOLLOW_PROGRESS,
    dictEnum.CONTACT_STATUS,
    dictEnum.SEX,
  ])

  modalConfig.universityColumns = [
    { dataIndex: "code", key: "code", title: "学校编码" },
    { dataIndex: "schoolEnName", key: "schoolEnName", title: "学校名称", },
    {
      dataIndex: "schFollowUpProgress",
      key: "schFollowUpProgress",
      title: "跟进进度",
      cellRender: (record, data) => {
        if (dictLists.data[dictEnum.FOLLOW_PROGRESS]) {
          const item = dictLists.data[dictEnum.FOLLOW_PROGRESS].find(v => v.value == data)
          return item ? item.label : ''
        }
        return ''
      }
    },
  ]

  modalConfig.responsibleColumns = [
    { dataIndex: "nickname", key: "nickname", title: "用户名称" },
    { dataIndex: "deptName", key: "deptName", title: "所属部门" },
    { dataIndex: "postName", key: "postName", title: "职位" },
  ]
})
onBeforeMount(() => {
  console.log('onBeforeMount');
})
onBeforeUpdate(() => {
  console.log('onBeforeUpdate');
})
onUpdated(() => {
  console.log('onUpdated');
})
onBeforeUnmount(() => {
  console.log('onBeforeUnmount');
})
onUnmounted(() => {
  console.log('onUnmounted');
})

const resetForm = () => {
  formRef.value.resetFields()
}

const onSubmit = () => {
  formRef.value.validate().then(() => {
    isLoading = true
    if (route.query.id) {
      updateItem(formState.state)
    } else {
      saveItem(formState.state)
    }
  })
};

const saveItem = (data) => {
  save(data).then(res => {
    if (res.code === 200) {
      message.success(res.msg)
      returnRoute()
    }
    if (res.code === 500) return message.error(res.msg || '新增失败，服务器错误')
    isLoading = false
  }).catch(() => isLoading = false)
}

const updateItem = (data) => {
  update(data).then(res => {
    if (res.code === 200) {
      message.success(res.msg)
      returnRoute()
    }
    if (res.code === 500) return message.error(res.msg || '编辑失败，服务器错误')
    isLoading = false
  }).catch(() => isLoading = false)
}

const openDialog = (type) => {
  modalConfig.currentType = type
  modalConfig.commonColumns = type === 'schName' ? modalConfig.universityColumns : modalConfig.responsibleColumns
  modalConfig.api = type === 'schName' ? schoolPage : userPage
  modalConfig.title = type === 'schName' ? '选择学校' : '选择负责人'
  modalConfig.show = true
  modalConfig.searchForm = type === 'schName' ? [
    {
      label: '学校名称',
      type: 'input',
      key: 'schoolCnName',
      placeholder: '请输入',
    }
  ] : [
    {
      label: '用户名称',
      type: 'input',
      key: 'nickname',
      placeholder: '请输入',
    }
  ]
}

const closeDialog = () => {
  modalConfig.show = false
}

const selectItem = (value, type) => {
  if (type === 'schName') {
    formState.state.schId = value.id
    formState.state.schName = value.schoolEnName
  } else {
    formState.state.responsiblePerson = value.nickname
    formState.state.responsiblePersonId = value.id
  }
}

</script>
